# -*- coding: utf-8 -*-
from pyquery import PyQuery
from cec.items import CecSku
from zc_core.model.items import Catalog, ItemDataSupply, MissItemData
from zc_core.util.http_util import *
import json
from zc_core.pipelines.helper.catalog_helper import CatalogHelper

# 解析catalog列表
def parse_catalog(response):
    jpy = PyQuery(response.text)
    cats = list()
    for catalog1_jpy in [i for i in jpy('.menu li').items()]:
        cat1_id = str(re.search('\d+', catalog1_jpy('.class h4 a').attr('href')).group())
        cat2_name = catalog1_jpy('.class h4 a').text()
        cat1 = _build_catalog(cat1_id, cat2_name, '', 1)
        cats.append(cat1)
        for catalog2_jpy in [i for i in catalog1_jpy('dl').items()]:
            cat2_name = catalog2_jpy('h3 a').text()
            cat2_id = str(re.search('\d+', catalog2_jpy('h3 a').attr('href')).group())
            cat2 = _build_catalog(cat2_id, cat2_name, cat1_id, 2)
            cats.append(cat2)
            for catalog3_jpy in [i for i in catalog2_jpy('.goods-class').items()]:
                cat3_id = str(re.search('\d+', catalog3_jpy('a').attr('href')).group())
                cat3_name = catalog3_jpy('a').text()
                cat3 = _build_catalog(cat3_id, cat3_name, cat2_id, 3)
                cats.append(cat3)
    return cats


def _build_catalog(cat_id, cat_name, parent_id, level):
    cat = Catalog()
    cat['catalogId'] = cat_id
    cat['catalogName'] = cat_name
    cat['parentId'] = parent_id
    cat['level'] = level
    if level == 3:
        cat['leafFlag'] = 1
    else:
        cat['leafFlag'] = 0
    cat['linkable'] = 0
    return cat


# 维度：三级分页，解析sku列表页数
def parse_total_page(response):
    jpy = PyQuery(response.text)
    total_page = int([i.text() for i in jpy('.page span').items()][-1].split('/')[-1])
    return total_page


# 解析sku列表
def parse_sku(response):
    meta = response.meta
    batch_no = meta.get('batchNo')
    catalog_id = meta.get('catalogId')
    jpy = PyQuery(response.text)
    skus = list()
    sku_list_id = [re.search('\d+', i('a').attr('href')).group() for i in jpy('.goodslist_name').items()]
    sku_list_name = [i('a').attr('title') for i in jpy('.goodslist_name').items()]
    sku_list_sold_count = [i.text() for i in jpy('.status').items()]
    sku_list_supplierName = [[j('a').text() for j in i('li').items() if j('p').text() == "供应商"] for i in
                             jpy('.goodslist_sell').items()]
    for index, skuid in enumerate(sku_list_id):
        sku = CecSku()
        sku['skuId'] = skuid
        sku['skuName'] = sku_list_name[index]
        sku['batchNo'] = batch_no
        sku['catalog3Id'] = catalog_id
        sku['soldCount'] = int(sku_list_sold_count[index])
        sku['supplierName'] = sku_list_supplierName[index][0]
        CatalogHelper().fill(sku)
        skus.append(sku)
    return skus


def parse_item_data(response):
    meta = response.meta
    batch_no = meta.get('batchNo')
    sku_id = meta.get('skuId')
    catalog3Id = meta.get('catalog3Id')
    # pool_list = meta.get('poolList')
    soldCount = meta.get('soldCount')
    supplierName = meta.get('supplierName')
    jpy = PyQuery(response.text)
    result = CecSku()
    skuName = jpy('.name h1').text()
    result['batchNo'] = batch_no
    result['skuId'] = sku_id
    result['skuName'] = skuName
    result['soldCount'] = soldCount
    result['catalog3Id'] = catalog3Id
    CatalogHelper().fill(result)
    # 三级分页名称
    # catalog3Name = [i['catalogName'] for i in pool_list if i.get('_id') == catalog3Id][0]
    # result['catalog3Name'] = catalog3Name
    # # 二级分页id
    # catalog2Id = [i['parentId'] for i in pool_list if i.get('_id') == catalog3Id][0]
    # result['catalog2Id'] = catalog2Id
    # # 二级分页名称
    # catalog2Name = [i['catalogName'] for i in pool_list if i.get('_id') == catalog2Id][0]
    # result['catalog2Name'] = catalog2Name
    # # 一级分页id
    # catalog1Id = [i['parentId'] for i in pool_list if i.get('_id') == catalog2Id][0]
    # result['catalog1Id'] = catalog1Id
    # # 一级分页名称
    # catalog1Name = [i['catalogName'] for i in pool_list if i.get('_id') == catalog1Id][0]
    # result['catalog1Name'] = catalog1Name
    originPrice = jpy('.mark_price strong').text()
    result['originPrice'] = float(originPrice)
    mainImgs = [i('img').attr('src') for i in jpy('.selected').items()]
    if mainImgs.__len__() == 0:
        mainImgs = jpy('.thumblist .last img').attr('src')
    else:
        mainImgs = mainImgs[0]
    result['skuImg'] = mainImgs
    brandName_list = [i('td').text() for i in jpy('.rer_para tbody tr').items() if i('th').text() == '品牌：']
    if brandName_list.__len__() != 0:
        brandName = brandName_list[0]
        result['brandName'] = brandName
    unit_list = [i('td').text() for i in jpy('.rer_para tbody tr').items() if i('th').text() == '计价单位：']
    if unit_list.__len__() != 0:
        unit = unit_list[0]
        result['unit'] = unit
    supplier_list = [i('td').text() for i in jpy('.rer_para tbody tr').items() if i('th').text() == '供应商：']
    if supplier_list.__len__() != 0:
        supplier_name = supplier_list[0]
        if supplier_name.__len__() != 0:
            result['supplierName'] = supplier_name
    supplierSkuId_list = [i('p').text() for i in jpy('.be_worth').items() if i('span').text() == "商品货号"]
    if supplierSkuId_list.__len__() != 0:
        supplierSkuId = supplierSkuId_list[0]
        result['supplierSkuId'] = supplierSkuId
        result['supplierSkuCode'] = supplierSkuId
    result['supplierName']=supplierName
    return result


def parse_prices(response):
    meta = response.meta
    batch_no = meta.get('batchNo')
    sku_id = meta.get('skuId')
    json_data = json.loads(response.text)
    item = ItemDataSupply()
    item['batchNo'] = batch_no
    item['skuId'] = sku_id
    item['salePrice'] = json_data['data'][0]['price']
    item['stock'] = str(json_data['data'][0]['store'])

    return item


if __name__ == '__main__':
    pass
